# -*- coding: utf-8 -*-
"""
Created on Tue Aug 16 15:59:19 2022

@author: wulong
"""
import numpy as np
from casadi import *
from Basic_paras import *

# In[1] Day-ahead model
# States
def ode_ies_h(x_h, uc, uz, ud):
    dxdt = SX.zeros(Nx_h)
    
    C_soc = x_h[0]
    C_sot = x_h[1]
    tbr = x_h[2]
    
    Gff = uc[0]
    Gfm = uc[1]
    Nec = uc[2]
    Gstu = uc[3]
    Pbar = uc[4]
    
    zfc = uz[0]
    zma = uz[1]
    zec = uz[2]
    zst = uz[3]
    
    ta = ud[0]
    Sra = ud[1]
    Pd = ud[2]
    Qother = ud[3]
    
    Gst = zst*Gstu + (zst - 1)*Gstu
    Pmt = k_mt*Gfm
    Qab = k_ab*Pmt
    Qec = k_ec*Nec
    Qst = k_st*Gst
    Qsl = Qab + Qec + Qst
    
    dxdt[0] = k_ba*Pbar
    dxdt[1] = -Gst/Mst
    dxdt[2] = (Ubr*(ta - tbr) - Qsl + Qother)/Cbr
    
    return dxdt

# Outputs
def out_ies_h(x_h, uc, uz, ud):
    y_alg = MX.zeros(Ny_h)
    
    C_soc = x_h[0]
    C_sot = x_h[1]
    tbr = x_h[2]
    
    Gff = uc[0]
    Gfm = uc[1]
    Nec = uc[2]
    Gstu = uc[3]
    Pbar = uc[4]
    
    zfc = uz[0]
    zma = uz[1]
    zec = uz[2]
    zst = uz[3]
    
    ta = ud[0]
    Sra = ud[1]
    Pd = ud[2]
    Qother = ud[3]
    
    Gall = zma*Gab0 + zec*Gec0 + Gstu
    Ppv = k_pv*Sra
    Pfc = k_fc*Gff
    Pmt = k_mt*Gfm
    Qec = k_ec*Nec
    Pcp = k_cp*Qec
    Ppmp = k_pmp*Gall
    Psl = Ppv + Pfc + Pmt + Pbar - Pcp - Ppmp - Pd
    
    y_alg[0] = Psl
    y_alg[1] = tbr
    
    return y_alg

# In[2] Formulate discrete time dynamics
x_sym_h = SX.sym('x_h', Nx_h)
uc_sym_h = SX.sym('uc_h', Nuc_h)
uz_sym_h = SX.sym('uz_h', Nuz_h)
ud_sym_h = SX.sym('ud_h', Nud_h)

ode_sym_h = ode_ies_h(x_sym_h, uc_sym_h, uz_sym_h, ud_sym_h)
args_h = {'x': x_sym_h, 'p': vertcat(uc_sym_h, uz_sym_h, ud_sym_h), 'ode': ode_sym_h}
opts_h = {'tf': Delta_h, 'regularity_check': True}
I_ode_h = integrator('I_ode_h', 'rk', args_h, opts_h)
